﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DotNetDream.WebMetroEngine.Mvc.Repository;
using DotNetDream.WebMetroEngine.Mvc.Models;
using Benecura.Interfaces.WebMetro.Models;
using System.IO;
using System.Web.Hosting;

namespace Benecura.Interfaces.WebMetro.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            //TODO: Load logged in Domain
            return View(new DomainModules { DomainId = 1, ModuleNameFilter = "" });
        }

        /// <summary>
        /// Get selected module partial view
        /// </summary>
        /// <param name="moduleId"></param>
        /// <returns></returns>
        [HttpGet]
        public JsonResult GetModuleFullView(string moduleId)
        {
            //Default as not found
            string viewName = "_wmeNotFound";
            Tile fullTile = null;

            int id = 0;
            //Module Id valid
            if (int.TryParse(moduleId, out id))
            {
                var db = new ModuleRepository();

                //Find module
                var module = db.Select<Module>(m => m.Id == id).FirstOrDefault();
                //Find full view tile
                if (module != null)
                {
                    fullTile = module.Tiles.FirstOrDefault(t => t.Type.Name.ToLower().Equals("full"));
                    //Tile found and has parial view defined
                    if (fullTile != null && !string.IsNullOrEmpty(fullTile.PartialView))
                    {
                        //Partial view exists in the system
                        if (HomeController.ViewExists(fullTile.PartialView, "Shared"))
                        {
                            viewName = fullTile.PartialView;
                        }
                    } //End if tile has full view
                } //End if module is found
                //} //End using
            } //End parse module Id

            //Retrieve Tile full view
            if (fullTile == null) fullTile = new Tile { PartialView = "Full Tile" };
            return Json(PartialViewHTML(viewName, fullTile), JsonRequestBehavior.AllowGet);
        }
        /// <summary>
        /// Get the markup HTML of a partial view
        /// </summary>
        /// <param name="viewName"></param>
        /// <param name="model"></param>
        /// <returns></returns>
        public string PartialViewHTML(string name, object model)
        {
            this.ViewData.Model = model;
            try
            {
                using (StringWriter sw = new StringWriter())
                {
                    ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, name);
                    ViewContext viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
                    viewResult.View.Render(viewContext, sw);

                    return sw.GetStringBuilder().ToString();
                }
            }
            catch (Exception ex)
            {
                return ex.ToString();
            }
        }

        /// <summary>
        /// Find if a view exists in the system
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public static bool ViewExists(string name, string folder)
        {
            //Check physical location, view name can contain .cshtml or not
            FileInfo file = new FileInfo(Path.Combine(HostingEnvironment.ApplicationPhysicalPath, "Views", folder, (name.EndsWith(".cshtml")) ? name : name + ".cshtml"));
            return file.Exists;
        }
    }
}
